import { REMOVE_USER_TOKENID_TYPE, UPDATE_USER_TOKENID_TYPE } from './types'

const userModule = {
  namespaced: true,
  state: () => ({
    token: '',
    userid: ''
  }),
  getters: {
    isLogined: state => !!state.userid
  },
  mutations: {
    [UPDATE_USER_TOKENID_TYPE] (state, payload) {
      state.token = payload.token
      state.userid = payload.userid
    },
    [REMOVE_USER_TOKENID_TYPE] (state) {
      state.token = ''
      state.userid = ''
    }
  },
  actions: {
    updateUserIdAndToken (context, payload) {
      localStorage.setItem('user__token', payload.token)
      localStorage.setItem('user__userid', payload.userid)
      context.commit({ type: UPDATE_USER_TOKENID_TYPE, ...payload })
    },
    initUserIdAndToken (context) {
      const token = localStorage.getItem('user__token') || ''
      const userid = localStorage.getItem('user__userid') || ''
      context.commit({ type: UPDATE_USER_TOKENID_TYPE, token, userid })
    },
    removeTokenAndId (context) {
      localStorage.removeItem('user__token')
      localStorage.removeItem('user__userid')
      context.commit({ type: REMOVE_USER_TOKENID_TYPE })
    }
  }
}
export default userModule
